package com.wbxqy.car_management_system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wbxqy.car_management_system.entity.CarRequest;
import com.wbxqy.car_management_system.entity.Trip;
import com.wbxqy.car_management_system.service.ICarRequestService;
import com.wbxqy.car_management_system.service.ICarService;
import com.wbxqy.car_management_system.service.ITripService;
import com.wbxqy.car_management_system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 行程表 前端控制器
 * </p>
 *
 * @author wbxqy
 * @since 2024-07-04
 */
@RestController
@RequestMapping("/wbxqy/trip")
public class TripController {
    @Autowired
    private ITripService tripService;
    @Autowired
    private ICarRequestService carRequestService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ICarService carService;


    @PostMapping
    public boolean addTrip(@RequestBody Trip trip) {
        return tripService.save(trip);
    }

    @DeleteMapping("/{id}")
    public boolean deleteTrip(@PathVariable Integer id) {
        return tripService.removeById(id);
    }

    @PutMapping
    public boolean updateTrip(@RequestBody Trip trip) {
        return tripService.updateById(trip);
    }

    @GetMapping("/{id}")
    public Trip getTripById(@PathVariable Integer id) {
        return tripService.getById(id);
    }

    @GetMapping("/page")
    public Page<Trip> getAllTripsPage(@RequestParam(required = false, defaultValue = "1") Integer page,
                                      @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                      @RequestParam(required = false) String startLocation,
                                      @RequestParam(required = false) String endLocation,
                                      @RequestParam(required = false) String tripStatus) {
        // 构造分页构造器
        Page<Trip> pageInfo = new Page<>(page, pageSize);
        QueryWrapper<Trip> queryWrapper = new QueryWrapper<>();

        // 添加过滤条件
        if (startLocation != null && !startLocation.isEmpty()) {
            queryWrapper.like("start_location_wbxqy", startLocation);
        }
        if (endLocation != null && !endLocation.isEmpty()) {
            queryWrapper.like("end_location_wbxqy", endLocation);
        }
        if (tripStatus != null && !tripStatus.isEmpty()) {
            queryWrapper.eq("trip_status_wbxqy", tripStatus);
        }
        // 执行分页查询
        final Page<Trip> tripPage = tripService.page(pageInfo, queryWrapper);
        for (Trip trip : tripPage.getRecords()) {
            CarRequest carRequest = null;
            if (trip.getRequestIdWbxqy() != null) {
                carRequest = carRequestService.getFullRequest(trip.getRequestIdWbxqy());
            }
            trip.setCarRequest(carRequest);
        }

        return pageInfo;
    }

    /**
     * 创建行程
     *
     * @param tripDTO
     * @return
     */
    @PostMapping("/create")
    public ResponseEntity<?> createTrip(@RequestBody Trip tripDTO) {
        Trip trip = new Trip();
        trip.setRequestIdWbxqy(tripDTO.getRequestIdWbxqy());
        trip.setStartLocationWbxqy(tripDTO.getStartLocationWbxqy());
        trip.setEndLocationWbxqy(tripDTO.getEndLocationWbxqy());
        trip.setStartTimeWbxqy(tripDTO.getStartTimeWbxqy());
        trip.setEndTimeWbxqy(null); // 初始设置为空
        trip.setTripStatusWbxqy("S");
        trip.setCreateTimeWbxqy(LocalDateTime.now());

        tripService.save(trip);

        return ResponseEntity.ok("建立");
    }

    /**
     * 开始行程
     *
     * @param tripDTO
     * @return
     */
    @PutMapping("/start")
    public ResponseEntity<?> startTrip(@RequestBody Trip tripDTO) {
        Trip trip = tripService.getById(tripDTO.getTripIdWbxqy());
        if (trip == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("没有改行程");
        }
        trip.setImageUrlWbxqy(tripDTO.getImageUrlWbxqy());
        trip.setTripStatusWbxqy("I");
        trip.setUpdateTimeWbxqy(LocalDateTime.now());

        tripService.updateById(trip);

        return ResponseEntity.ok("开始");
    }

    /**
     * 结束行程
     *
     * @param tripDTO
     * @return
     */
    @PutMapping("/end")
    public ResponseEntity<?> endTrip(@RequestBody Trip tripDTO) {
        System.out.println(tripDTO.getTripIdWbxqy());
        System.out.println(tripDTO.getDistanceWbxqy());
        Trip trip = tripService.getById(tripDTO.getTripIdWbxqy());
        if (trip == null) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("没有改行程");
        }

        trip.setEndTimeWbxqy(LocalDateTime.now());
        trip.setDistanceWbxqy(tripDTO.getDistanceWbxqy());
        trip.setTripStatusWbxqy("E");
        trip.setUpdateTimeWbxqy(LocalDateTime.now());

        tripService.updateById(trip);

        return ResponseEntity.ok("结束");
    }

    @GetMapping("/list")
    public List<Trip> listTrip(@RequestParam Integer requestId) {
        System.out.println(requestId);
        final QueryWrapper<Trip> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("request_id_wbxqy", requestId);
        // 获取未排序的Trip列表
        List<Trip> trips = tripService.list(queryWrapper);

        // 使用自定义Comparator对列表进行排序
        trips.sort((trip1, trip2) -> {
            // 定义状态优先级顺序
            List<String> order = Arrays.asList("S", "I", "E");
            return Integer.compare(order.indexOf(trip1.getTripStatusWbxqy()), order.indexOf(trip2.getTripStatusWbxqy()));
        });

        return trips;
    }
}
